/*!
 @header ConfirmPayViewController.m
 @author 王 文彬
 @version 1.0.0 2013/02/06 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "ConfirmPayViewController.h"
#import "Helper.h"
#import "Config.h"
#import <QuartzCore/QuartzCore.h>
#import "JMFBase.h"
#import "RechargeViewController.h"

@interface ConfirmPayViewController ()

@end

//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：ConfirmPayViewController的业务逻辑相对简单，重点则是VC的dismiss逻辑，详见全局变量_parentDisFlag的注释。
//
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>

@implementation ConfirmPayViewController

@synthesize dismissModal = _dismissModal;
@synthesize delegate = _delegate;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithOrder:(NSDictionary *)order
{
    self = [super init];
    if (self) {
        _order = order;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = _L(@"vc_title_008");   //确认付款
    
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    

    UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 100)];
    view1.layer.cornerRadius = 3;
    view1.layer.borderColor = [_SYS_COLOR_002 CGColor];
    view1.layer.borderWidth = 1;
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    
    //订单金额背景view
    UIView *amountBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 70, 300, 30)];
    amountBgView.backgroundColor = [UIColor colorWithRed:244/255.0f green:244/255.0f blue:244/255.0f alpha:1.0f];
    [view1 addSubview:amountBgView];
    
    UILabel* productTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 60, 20)];
    productTitleLabel.text = _L(@"title_name_03");     
    productTitleLabel.font = _SYS_FONT_004;
    [view1 addSubview:productTitleLabel];
    
    UILabel* amountTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 60, 20)];
    amountTitleLabel.text = _L(@"title_75");    
    amountTitleLabel.font = _SYS_FONT_004;
    amountTitleLabel.backgroundColor = [UIColor clearColor];
    [amountBgView addSubview:amountTitleLabel];
    
    
    _productNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, 200, 20)];
    _productNameLabel.font = _SYS_FONT_004;
    _productNameLabel.textColor = _SYS_COLOR_002;
    _productNameLabel.text = _order[@"product"][@"name"];
    [view1 addSubview:_productNameLabel];
    
    _contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 30, 220, 30)];
    _contentLabel.textColor = _SYS_COLOR_003;
    _contentLabel.font = _SYS_FONT_003;
    _contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
    _contentLabel.numberOfLines = 0;
    _contentLabel.text = _order[@"product"][@"description"];
    [view1 addSubview:_contentLabel];
    
    _amountLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 5, 200, 20)];
    _amountLabel.textColor = [UIColor colorWithRed:224/255.0 green:109/255.0 blue:26/255.0 alpha:1.0f];
    _amountLabel.font = _SYS_FONT_003;
    _amountLabel.backgroundColor = [UIColor clearColor];
    _amountLabel.text = [NSString stringWithFormat:_L(@"title_amount_04"), [_order[@"amount"] floatValue]];  //%.2f元
    [amountBgView addSubview:_amountLabel];
    
    UIView* view2 = [[UIView alloc] initWithFrame:CGRectMake(10, 120, 300, 80)];
    view2.layer.cornerRadius = 3;
    view2.layer.borderColor = [_SYS_COLOR_002 CGColor];
    view2.layer.borderWidth = 1;
    view2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view2];
    
    
    UILabel* accountTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 80, 20)];
    accountTitleLabel.text = _L(@"title_name_02");     //当前账户
    accountTitleLabel.font = _SYS_FONT_004;
    [view2 addSubview:accountTitleLabel];
    
    UILabel* cashTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 80, 20)];
    cashTitleLabel.text = _L(@"title_amount_05");      //可用余额
    cashTitleLabel.font = _SYS_FONT_004;
    [view2 addSubview:cashTitleLabel];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 10, 200, 20)];
    _nameLabel.font = _SYS_FONT_004;
    _nameLabel.textColor = [UIColor colorWithRed:124/255.0 green:124/255.0 blue:124/255.0 alpha:1.0f];
    [view2 addSubview:_nameLabel];
    
    _cashLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 40, 200, 20)];
    _cashLabel.textColor = [UIColor colorWithRed:129/255.0 green:153/255.0 blue:37/255.0 alpha:1.0f];
    _cashLabel.font = _SYS_FONT_003;
    [view2 addSubview:_cashLabel];
    
    
    UIView* view3 = [[UIView alloc] initWithFrame:CGRectMake(10, 210, 300, 150)];
    view3.layer.cornerRadius = 3;
    view3.tag = 103;
    view3.layer.borderColor = [_SYS_COLOR_002 CGColor];
    view3.layer.borderWidth = 1;
    view3.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view3];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 5.0f, 300.0f, 25.0f)];
    titleLabel.text = _L(@"title_15");
    titleLabel.font = _SYS_FONT_006;
    titleLabel.textAlignment = UITextAlignmentCenter;
    [view3 addSubview:titleLabel];
    
    UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, Y_AND_HEIGHT(titleLabel.frame)+5.0f, 300.0f, 0.5f)];
    lineImageView.image = [UIImage imageNamed:@"com_bg_008"];
    [view3 addSubview:lineImageView];
    
    _balanceTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, Y_AND_HEIGHT(lineImageView.frame)+9.0f, 280, 17)];
    _balanceTitleLabel.font = _SYS_FONT_004;
    _balanceTitleLabel.textColor = [UIColor colorWithRed:224/255.0 green:118/255.0 blue:37/255.0 alpha:1.0f];
    [view3 addSubview:_balanceTitleLabel];        
    
    _tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, Y_AND_HEIGHT(_balanceTitleLabel.frame), 280.0f, 70.0f)];
    _tipsLabel.font = _SYS_FONT_003;
    _tipsLabel.numberOfLines = 4;
    _tipsLabel.textColor = _SYS_COLOR_003;
    _tipsLabel.text = _L(@"holder_58");
    _tipsLabel.hidden = YES;
    [view3 addSubview:_tipsLabel];
    
    _rechargeButton = [[UIButton alloc] initWithFrame:CGRectMake(_SYS_SCREEN_WIDTH-20-56-10,Y_AND_HEIGHT(lineImageView.frame)+5.0f, 56.0f, 26.5f)];
    [_rechargeButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_btn_005_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    _rechargeButton.titleLabel.font = _SYS_FONT_001;
    [_rechargeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _rechargeButton.hidden = YES;
    [_rechargeButton setTitle:_L(@"btn_yes_21") forState:UIControlStateNormal];
    [_rechargeButton addTarget:self action:@selector(buttonRechargeEvent) forControlEvents:UIControlEventTouchUpInside];
    [view3 addSubview:_rechargeButton];
    
    _payButton = [[UIButton alloc] initWithFrame:CGRectMake(10, _SYS_FRAME_HEIGHT -44 - 20 - 40, 300, 40)];
    _payButton.titleLabel.font = _SYS_FONT_009;
    [_payButton setTitle:_L(@"btn_yes_03") forState:UIControlStateNormal];   //确认付款
    [_payButton addTarget:self action:@selector(buttonPayEvent) forControlEvents:UIControlEventTouchUpInside];

    [_payButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_006_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [self.view addSubview:_payButton];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*!
 @abstract view显示的时候就要请求用户的账户信息
 */
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_GET_ACCOUNT];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    [request asynchronous];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    if (_parentDisFlag) {
        [_delegate closeViewController];
    }
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent
{
    if (_dismissModal) {
        [self.navigationController dismissModalViewControllerAnimated:true];
    }
    else {
        [self.navigationController popViewControllerAnimated:true];
    }
}

/*!
 @abstract 确认付款按钮事件
 向服务器异步请求确认付款，传递参数为订单ID
 */
- (void)buttonPayEvent
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ORDER_PAYMENT];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_04");
    [request setSuccessSelector:@selector(paySuccessSelector:)];
    [request setValue:[_order valueForKey:@"id"] forParameter:@"productOrderId"];
    [request asynchronous];
}

- (void)buttonRechargeEvent
{
    //充值
    RechargeViewController *rechargeVC = [[RechargeViewController alloc] init];
    UINavigationController *rechargeNC = [[UINavigationController alloc] initWithRootViewController:rechargeVC];
    [Helper navigationControllerCommonStyle:rechargeNC];
    [self.navigationController presentModalViewController:rechargeNC animated:YES];
}

#pragma mark - JSONRequestDelegate

/*!
 @abstract 确认付款请求成功selector
 */
- (void)paySuccessSelector:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {
        
        [Helper showAllTextDialog:_L(@"alert_72") inView:nil];
        //确认付款后，要让确认订单VC自动被dismiss掉
        _parentDisFlag = true;
        [self backButtonEvent];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }

}

/*!
 @abstract 用户账户信息请求成功后的代理方法
 将得到的账户信息赋给view的Label
 */
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {

        NSDictionary* info = [dict valueForKey:@"data"];
        _cashLabel.text = [NSString stringWithFormat:_L(@"title_amount_04"), [[info valueForKey:@"balance"] floatValue]];  //￥%.2f元
        
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_GET_BASICINFO];
        [request setValue:_ACCOUNT_ID forParameter:@"userId"];
        NSDictionary* responseData = [request synchronous];
        
        _nameLabel.text = responseData[@"data"][@"realName"];
        
        //判断余额是否充足
        //不足，提示用户充值，否则进行付款
        
        //不足
        if ([_order[@"amount"] floatValue] > [[info valueForKey:@"balance"] floatValue]) {
            
            _balanceTitleLabel.text = _L(@"alert_56");
            _rechargeButton.hidden = NO;
            _tipsLabel.hidden = YES;
            
            [self.view viewWithTag:103].frame = CGRectMake(10, 210, 300, 80);
        }
        
        //足够
        else {
            
            _balanceTitleLabel.text = _L(@"alert_57");
            _rechargeButton.hidden = YES;
            _tipsLabel.hidden = NO;
            
            [self.view viewWithTag:103].frame = CGRectMake(10, 210, 300, 140);
            if (!iPhone5) {
                _payButton.frame = CGRectMake(10, Y_AND_HEIGHT([self.view viewWithTag:103].frame)+10, 300, 40);
            }
            
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

@end
